package core;

import gitobject.Commit;
import gitobject.Tree;
import repository.Repository;


import java.io.*;
import java.util.Arrays;


public class JitCheckout {

    public static void checkout(String branchName) throws IOException {
        File head = new File(Repository.getGitDir() + File.separator + "HEAD");
        String branch = "ref: refs" + Tree.treeSeparator + "heads" + Tree.treeSeparator + branchName + "\n";
        String filepath = Repository.getGitDir() + File.separator + "refs" + File.separator + "heads";
        String[] branchList = new File(filepath).list();
        assert branchList != null;
        if(Arrays.asList(branchList).contains(branchName)){
            try {
                FileWriter fw = new FileWriter(head, false);
                fw.write(branch);
                fw.flush();
                fw.close();
                //git会在存在差异时删除原来没有的文件，这里只会重置map，相当于--soft的reset，但不保存回退的index，只保留当前没有commit的index。
                JitMap.initial();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Switched to branch '" + branchName + "'");
        }
        else {
            System.out.println("error: pathspec '" + branchName + "' did not match any branch(es) known to jit");
            throw new IOException("error: pathspec '" + branchName + "' did not match any branch(es) known to jit");
        }
    }

    public static void checkoutB(String branchName) throws IOException {
        String filepath = Repository.getGitDir() + File.separator + "refs" + File.separator + "heads";
        String[] branchList = new File(filepath).list();
        assert branchList != null;
        if (Arrays.asList(branchList).contains(branchName)) {  // 存在则重置
            String headcontext = JitBranch.readFile(new File(Repository.getGitDir() + File.separator + "HEAD"));  //HEAD里面的内容
            String headPointer = headcontext.substring(16).trim();  // 从ref: refs/heads/master第16位开始取,例如：master
            String currentCommit = JitBranch.readFile(new File(filepath+File.separator+headPointer));  //当前的指针的commit内容
            // 重写已经存在的那个branch的commit
            File branchExist = new File(filepath+File.separator+branchName);
            try {
                FileWriter fw = new FileWriter(branchExist, false);
                fw.write(currentCommit);
                fw.flush();
                fw.close();
                JitMap.initial();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("The branch exists and successfully updates");
        } else {  // 不存在就新建加切换
            JitBranch.newBranch(branchName);
            checkout(branchName);
            System.out.println("branch '" + branchName + "' already exists and has been switched");
        }
    }

}
